The complete program is given below.
total
is declared to be of double
type,
since the sum of the doubles in the array will be a double.
It is initialized to zero.
Sums should be initialized to zero as a matter of course.
class SumArray { public static void main ( String[] args ) { double[] array = { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ; // declare and initialize the total double total = 0.0 ; // add each element of the array to the total for ( int index=0; index < array.length; index++ ) { total = total + array[ index ] ; } System.out.println("The total is: " + total ); } }
The program visits each element of the array, in order, adding each to the total.
When the loop exits, total
will be correct.
The statement
total = total + array[ index ] ;
would not usually be used.
It is more common to use the +=
operator:
total += array[ index ] ;
If you know the sum of the elements in an array of numbers,
and know how many elements there are,
how can you compute the average
of the elements?